package com.jzy.app.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jzy.app.dto.AppInfoDto;
import com.jzy.app.entity.AppInfo;
import com.jzy.app.entity.AppVersion;
import com.jzy.app.mapper.AppInfoDao;
import com.jzy.app.mapper.AppVersionDao;
import com.jzy.app.service.AppInfoService;
import com.jzy.app.sys.AppInfoContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;


@Service
public class AppInfoServiceImpl implements AppInfoService {


    @Autowired
    AppInfoDao appInfoDao;

    @Autowired
    AppVersionDao appVersionDao;

    @Override
    public PageInfo<AppInfo> getPage(AppInfoDto appInfoDto, Integer pageNum) {
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        PageHelper.startPage(pageNum,5,"id desc");
        return new PageInfo<>(appInfoDao.queryAllBy(appInfo));
    }

    @Override
    public int saveUpdate(AppInfo appInfo) {
        int num = 0;
        if (appInfo.getId()==null){
            num= appInfoDao.insert(appInfo);
        }else {
            num=appInfoDao.update(appInfo);
        }
        return num;
    }

    @Override
    public AppInfo getAppinfoId(Integer id) {
        return appInfoDao.queryById(Long.valueOf(id));
    }

    @Override
    public int delAppInfo(Integer id,HttpServletRequest request) {
        List<AppVersion> appVersions = appVersionDao.queryAllBy(new AppVersion().setAppid(Long.valueOf(id)));
        for (AppVersion appVersion : appVersions) {
            String realPath = request.getServletContext().getRealPath(appVersion.getDownloadlink());
            File file = new File(realPath);
            if (file.exists()){
                file.delete();
            }
            appVersionDao.deleteById(appVersion.getId());
        }

        AppInfo appInfo = appInfoDao.queryById(Long.valueOf(id));
        String realPath = request.getServletContext().getRealPath(appInfo.getLogopicpath());
        if (appInfo.getLogopicpath()!=null){
            File file = new File(realPath);
            if (file.exists()){
                file.delete();
            }
        }


        return appInfoDao.deleteById(Long.valueOf(id));
    }

    @Override
    public int sale(Integer id) {
        AppInfo appInfo = appInfoDao.queryById(Long.valueOf(id));
        if (appInfo.getStatus()== AppInfoContext.AppInfoStatus.on){
            appInfo.setStatus(5L);
        }else if (appInfo.getStatus()==AppInfoContext.AppInfoStatus.off){
            appInfo.setStatus(4L);
        }else if (appInfo.getStatus()==AppInfoContext.AppInfoStatus.yes){
            appInfo.setStatus(4L);
        }
        return appInfoDao.update(appInfo);
    }
}
